﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Microsoft.SharePoint;

using Kiiro.Model;
using Kiiro.Common.Entities;
using Kiiro.SiteDefinition.Core;
using Kiiro.Common.Utility;
using Microsoft.SharePoint.Utilities;
using Kiiro.SiteDefinition.ControlTemplates;

namespace Kiiro.SiteDefinition.ProjectPages
{
    public partial class Upload : BasePage
    {
        public int Type // 1 = folder, anything else is document
        {
            get { return Request.QueryString [ "Type" ] == null ? 0 : Convert.ToInt32 ( Request.QueryString [ "Type" ] ); }
        }

        public string RootFolder
        {
            get { return Request.QueryString [ "RootFolder" ] == null ? string.Empty : Request.QueryString [ "RootFolder" ]; }//Server.UrlDecode ( Request.QueryString [ "RootFolder" ] ); }
        }

        public AttachmentControl Attachments
        {
            get { return ( AttachmentControl ) attachmentControl; }
        }

        protected void Page_Load ( object sender, EventArgs e )
        {
            litTitle.Text = "Project Upload A Document";
            if ( KiiroMaster.V2Header.Project != null && !string.IsNullOrEmpty ( KiiroMaster.V2Header.Project.Title ) )
            {
                litTitle.Text = KiiroMaster.V2Header.Project.Title + " - Upload A Document";
            }

            if ( Type == 1 )
            {
                pnlFolder.Visible = true;
                pnlDocument.Visible = false;
            }
            else
            {
                pnlFolder.Visible = false;
                pnlDocument.Visible = true;
                Attachments.Title = "Document(s) to upload <span class='validation-message'>*</span>";

                if ( !Page.IsPostBack )
                {
                    Guid siteCollectionId = default ( Guid );
                    string serverRelativeUrl = default ( string );

                    SPHelpers.GetSiteCollectionIdAndServerRelativeUrl ( Request.Url.ToString ( ), out siteCollectionId, out serverRelativeUrl );
                    Setup setup = SetupModel.GetMidoriSetup ( siteCollectionId, serverRelativeUrl );

                    if ( setup != null && setup.SendEmailUpdates )
                        LoadTeamMembers ( );
                    else
                    {
                        EmailSection.Visible = false;
                        AttachmentSection.Attributes.Add ( "class", "row borderless" );
                    }
                }
            }

            if ( !Page.IsPostBack )
            {
                string qs = RootFolder == string.Empty ? "" : "?RootFolder=" + RootFolder;
                lnkBack.NavigateUrl = ServerRelativeUrl + Constants.ProjectFileUrls.Documents + qs;
            }
        }


        protected void btnUpload_Click ( object sender, EventArgs e )
        {
            UploadDocument ( Type == 1 );
        }

        protected void btnCancel_Click ( object sender, EventArgs e )
        {
            string qs = RootFolder == string.Empty ? "" : "?RootFolder=" + RootFolder;
            Response.Redirect ( ServerRelativeUrl + Constants.ProjectFileUrls.Documents + qs );
        }


        private void UploadDocument ( bool IsFolder )
        {
            Document document = new Document ( );
            document.IsFolder = IsFolder;
            document.ServerRelativeUrl = ServerRelativeUrl;
            document.SiteCollectionId = SiteCollectionId;
            document.FolderUrl = RootFolder == string.Empty ? ServerRelativeUrl + Constants.SPListUrls.Documents : RootFolder;

            Midori midori = new Midori ( );

            if ( IsFolder )
            {
                document.Title = txtFolderName.Text.Trim ( );
                midori.Documents.Add ( document );
            }
            else
            {
                //Loop through the attachments
                List<Attachment> attachments = Attachments.GetAttachments ( );
                if ( attachments != null && attachments.Count > 0 )
                {
                    foreach ( Attachment attachment in attachments )
                    {
                        document = new Document ( );
                        document.Title = attachment.FileName;
                        document.Description = attachment.Description;
                        document.FileBytes = attachment.Bytes;

                        document.IsFolder = IsFolder;
                        document.ServerRelativeUrl = String.IsNullOrEmpty ( RootFolder ) ? ServerRelativeUrl : ServerRelativeUrl + "/" + RootFolder;
                        document.SiteCollectionId = SiteCollectionId;
                        document.FolderUrl = RootFolder == string.Empty ? ServerRelativeUrl + Constants.SPListUrls.Documents : RootFolder;

                        midori.Documents.Add ( document );
                    }
                }
            }

            TeamMemberCollection members = TeamMembers1 as TeamMemberCollection;
            List<int> usersToNotify = members.GetSelectedIds ( );

            //Pass in list of documents
            if ( midori.Documents.Count > 0 )
            {
                midori = DocumentModel.Save ( midori, usersToNotify, CurrentUser, SiteCollectionId, ServerRelativeUrl );
            }

            Redirect ( midori );
        }

        private void LoadTeamMembers ( )
        {
            TeamMemberCollection teamCollection = ( TeamMemberCollection ) TeamMembers1;
            teamCollection.TeamMembers = TeamModel.GetTeamMembers ( SiteCollectionId, ServerRelativeUrl );
            teamCollection.ReadOnly = false;
        }

        private void Redirect ( Midori midori )
        {
            if ( midori.Documents.Count > 0 )
            {
                Attachments.ValidationMessage = "";
                bool allValid = true;
                foreach ( Document document in midori.Documents )
                {
                    if ( !document.IsValid ( ) )
                    {
                        lblFolderTitleMessage.Text = FormattingHelpers.GetErrorMessageText ( document.TitleMessage );

                        Attachments.ValidationMessage += FormattingHelpers.GetErrorMessageText ( document.TitleMessage );
                        Attachments.ValidationMessage += FormattingHelpers.GetErrorMessageText ( document.FileMessage );

                        allValid = false;
                    }
                }

                if ( allValid )
                {
                    string qs = RootFolder == string.Empty ? "" : "?RootFolder=" + Server.UrlEncode ( RootFolder );
                    Response.Redirect ( ServerRelativeUrl + Constants.ProjectFileUrls.Documents + qs );
                }
            }
            else
            {
                Attachments.ValidationMessage = "Document to upload is a required field.";
            }
        }
    }
}

/*************************************************************************
 * 
 * $Log: /Internal Projects/Kiiro/Kiiro.SiteDefinition/12/TEMPLATE/FEATURES/Kiiro.ProjectPages/Documents/Upload.aspx.cs $
 * 
 * 13    10/23/09 2:31p Adamw
 * 
 * 12    10/21/09 11:44a Adamw
 * Case 350, added a trim to the input text fields, added some clearer
 * error messages to document and folder name validation, removed isFolder
 * check from IsFolderNameValid as special chars are invlid for full url
 * 
 * 11    10/20/09 1:20p Adamw
 * Case 349b, to allow for + in filenames: removed URLDecoding of
 * documentUrl, added encoding of hrefs, and changed Source value on All
 * Documents to be Request.Url.PathAndQuery as relative url instead of the
 * oddly encoded Request.Url (encodes spaces as + and + as +)
 * 
 * 10    30/09/09 4:08p Camerons
 * Update all links that point to UserPages, pass User.SPUserId as the
 * ItemId so that we can safely run GetOrCreateUser
 * 
 * 9     30/09/09 9:51a Shafia
 * 
 * 8     17/08/09 11:07a Camerons
 * Added check-in comments section
 * 
 ************************************************************************/